package com.ruoyi.map.service.impl;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.index.domain.WeatherDto;
import com.ruoyi.map.domain.FhMapCityCollect;
import com.ruoyi.map.domain.FhMapWeather;
import com.ruoyi.map.mapper.FhMapWeatherMapper;
import com.ruoyi.map.service.IFhMapCityCollectService;
import com.ruoyi.map.service.IFhMapWeatherService;
import com.ruoyi.tools.HttpUtils;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author sangsijing
 * @since 2025/5/6 14:16
 */
@Service
public class FhMapWeatherServiceImpl implements IFhMapWeatherService {

    @Autowired
    private FhMapWeatherMapper fhMapWeatherMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IFhMapCityCollectService fhMapCityCollectService;

    @Override
    public FhMapWeather processCityWeather(FhMapWeather city) {
        // redis钥匙
        String key = Constants.LOGIN_MEMBER_TOKEN_KEY + city.getArea();
        String keyTime = key + "_time";
        Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
        String collectStatus = fhMapCityCollectService.getCollectStatus(userId, city.getArea());
        if (StringUtils.isNotEmpty(collectStatus)) {
            city.setStatus(collectStatus);
        } else {
            city.setStatus("0");
        }
        // 添加天气数据
        JsonObject day = this.commeonForecastList(city.getArea());
        String dayList = day.toString();
        Map<String, String> map = new HashMap<>();
        map.put("day", dayList);
        city.setWeatherDay(map);
        return city;
    }

    @Override
    public List<FhMapWeather> weatherList(FhMapWeather fhMapWeather) {

        //获取当前用户id
        Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();

        //根据城市名称条件筛选
        List<FhMapWeather> cityList = fhMapWeatherMapper.getCity(fhMapWeather.getArea());

        for (FhMapWeather city : cityList) {
            //redis钥匙
            String key = Constants.LOGIN_MEMBER_TOKEN_KEY+city.getArea();
            String keyTime = key+"_time";

            //保存是否收藏状态
            //根据用户id获取收藏状态
            String collectStatus = fhMapCityCollectService.getCollectStatus(userId,city.getArea());
            if (StringUtils.isNotEmpty(collectStatus)){
                city.setStatus(collectStatus);
            }else {
                city.setStatus("0");
            }

            //获取redis缓存
/*            Object cachedData = redisCache.getCacheObject(key);
            Object cacheTimeMillis = redisCache.getCacheObject(keyTime);
            if (cachedData != null){
                for (WeatherDay result : resultList) {

                    boolean useCache = false;
                    if (cachedData != null) {
                        // 数据有效（在5分钟内）
                        long currentTime = System.currentTimeMillis();
                        long currentRedisTime = (Long)cacheTimeMillis;
                        long fiveMinutesInMillis = 5 * 60 * 1000; // 5分钟的毫秒数
                        useCache = (currentTime - currentRedisTime) < fiveMinutesInMillis;
                        if (useCache){
                            String s = cachedData.toString();
                            Map<String, String> map = new HashMap<>();
                            map.put("day",s);
                            result.setWeatherDay(map);
                        }
                    }
                }
            }*/

            //添加天气数据
            JsonObject day = this.commeonForecastList(city.getArea());
            String dayList = day.toString();
            //调用15日天气和24小时温度
            Map<String, String> map = new HashMap<>();
            map.put("day", dayList);
            city.setWeatherDay(map);

            //设置redis缓存
            redisCache.setCacheObject(key, map);
            redisCache.setCacheObject(keyTime, System.currentTimeMillis());

        }
        return cityList;
    }


    @Override
    public List<FhMapCityCollect> myWeatherList(FhMapCityCollect fhMapCityCollect) {
        //获取当前用户id
        Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();

        //根据用户id条件筛选
        List<FhMapCityCollect> cityList = fhMapCityCollectService.getUserCity(userId);
        //如果用户没有收藏城市
        if (cityList.size() == 0){
            //返回一个写死的北京天气
            FhMapCityCollect fhMapCityCollect1 = new FhMapCityCollect();
            fhMapCityCollect1.setArea("北京市");
            cityList.add(fhMapCityCollect1);
        }
        if (StringUtils.isNotEmpty(fhMapCityCollect.getArea())){
            FhMapCityCollect fhMapCityCollect1 = new FhMapCityCollect();
            fhMapCityCollect1.setArea(fhMapCityCollect.getArea());
            //在插入前，还有个问题，如果添加的收藏城市已经存在，则不添加，但是还是要把这个排 在第一个
            if (cityList.contains(fhMapCityCollect1)){
                cityList.remove(fhMapCityCollect1);
            }
            cityList.add(0,fhMapCityCollect1);
        }
        for (FhMapCityCollect city : cityList) {
            //redis钥匙
            String key = Constants.LOGIN_MEMBER_TOKEN_KEY+city.getArea();
            String keyTime = key+"_time";

            //添加天气数据
            JsonObject day = this.commeonForecastList(city.getArea());
            String dayList = day.toString();
            //调用15日天气和24小时温度
            Map<String, String> map = new HashMap<>();
            map.put("day", dayList);
            city.setWeatherDay(map);

            //设置redis缓存
            redisCache.setCacheObject(key, map);
            redisCache.setCacheObject(keyTime, System.currentTimeMillis());

        }
        return cityList;
    }




    @Override
    public int weatherDelete(Long id) {
        return fhMapWeatherMapper.weatherDelete(id);
    }

    @Override
    public FhMapWeather weatherDetails(String area) {

        String key = Constants.LOGIN_MEMBER_TOKEN_KEY+area;

        //获取天气列表
        JsonObject day = this.commeonForecastList(area);
        JsonObject hour = this.commeonHour(area);
        String dayList = day.toString();
        String hourList = hour.toString();

        FhMapWeather fhMapWeather = new FhMapWeather();
        //调用15日天气和24小时温度
        Map<String, String> map = new HashMap<>();
        map.put("day",dayList);
        map.put("hour",hourList);
        fhMapWeather.setWeatherDay(map);
        //设置redis缓存
        redisCache.setCacheObject(key,map,5,TimeUnit.MINUTES);

        return fhMapWeather;
    }

    @Override
    public int weatherAdd(FhMapWeather fhMapWeather) {
        //获取天气列表
        JsonObject showapiResBody = this.commeonForecastList(fhMapWeather.getArea());
        JsonObject now = showapiResBody.get("cityInfo").getAsJsonObject();
        //城市编码
        String areaCode = now.get("c0").getAsString();
        //获取当前用户id
        Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
        fhMapWeather.setUserId(userId);
        fhMapWeather.setAreaCode(areaCode);

        return fhMapWeatherMapper.weatherAdd(fhMapWeather);
    }


    /*
    *  实时天气预报（万维易源）
    * */
    public JsonObject commeonForecastList(String area){
        String appcode = "e3761ef60a7e4983a1ae1c87829880d2";
        String host = "https://ali-weather.showapi.com";
        String path = "/area-to-weather";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("area", area);
        querys.put("needMoreDay", "1");
        querys.put("needAlarm", "1");

        try {
            //发送请求
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //获取响应实体
            HttpEntity entity = response.getEntity();
            //确保响应实体不为空
            if(entity!=null){
                //将响应实体转换为字符串
                String jsonString = EntityUtils.toString(entity);
                Gson gson = new Gson();
                //解析JSON字符串为JsonObject
                JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
                //提取值
                JsonObject showapiResBody = jsonObject.get("showapi_res_body").getAsJsonObject();
                return showapiResBody;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    /*
    *   24小时天气
    * */
    public JsonObject commeonHour(String area){
        String appcode = "e3761ef60a7e4983a1ae1c87829880d2";
        String host = "https://ali-weather.showapi.com";
        String path = "/hour24";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("area", area);
        querys.put("needMoreDay", "1");
        querys.put("needAlarm", "1");

        try {
            //发送请求
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //获取响应实体
            HttpEntity entity = response.getEntity();
            //确保响应实体不为空
            if(entity!=null){
                //将响应实体转换为字符串
                String jsonString = EntityUtils.toString(entity);
                Gson gson = new Gson();
                //解析JSON字符串为JsonObject
                JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
                //提取值
                JsonObject showapiResBody = jsonObject.get("showapi_res_body").getAsJsonObject();
                return showapiResBody;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    /*
     *  获取天气预报
     * */
    @Override
    public WeatherDto commeonForecast(String area){
        String appcode = "e3761ef60a7e4983a1ae1c87829880d2";
        String host = "https://ali-weather.showapi.com";
        String path = "/area-to-weather";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("area", area);
        querys.put("needMoreDay", "1");
        querys.put("needIndex", "1");
        querys.put("needAlarm", "1");
        querys.put("needHourData", "1");

        try {
            //发送请求
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //获取响应实体
            HttpEntity entity = response.getEntity();
            //确保响应实体不为空
            if(entity!=null){
                //将响应实体转换为字符串
                String jsonString = EntityUtils.toString(entity);
                Gson gson = new Gson();
                //解析JSON字符串为JsonObject
                JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
                //提取值
                JsonObject showapiResBody = jsonObject.get("showapi_res_body").getAsJsonObject();
                JsonObject now = showapiResBody.get("now").getAsJsonObject();
                //天气
                String weather = now.get("weather").getAsString();
                //温度
                String temperature = now.get("temperature").getAsString();
                //湿度
                String sd = now.get("sd").getAsString().replace("%", "");  // 去掉百分号;

                JsonObject f1 = showapiResBody.get("f1").getAsJsonObject();
                //日出时间，日落时间
                String sunBeginEnd = f1.get("sun_begin_end").getAsString();
                String weatherCode = f1.get("night_weather_code").getAsString();
                String airPress = f1.get("air_press").getAsString().replace("hPa", "").trim();

                WeatherDto weatherDto = new WeatherDto(weather, temperature, sd,sunBeginEnd,airPress,weatherCode);
                return weatherDto;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

}
